import 'package:flutter/services.dart';

/// app config
class AppConfig {
  static const String _TAG = 'AppConfig';

  // 工厂模式
  factory AppConfig() => _getInstance();

  static AppConfig get instance => _getInstance();

  static AppConfig? _instance;

  static AppConfig _getInstance() {
    if (_instance == null) {
      _instance = AppConfig._internal();
    }
    return _instance!;
  }

  static const String _dev = 'dev';
  static const String _stage = 'stage';
  static const String _test = 'test';
  static const String _release = 'release';

  AppConfig._internal() {
    // 根据dart-define 获取环境变量、编译时间
    // 备忘 fromEnvironment必须使用const方式
    _env = const String.fromEnvironment("ENV", defaultValue: _dev);
    if (const bool.hasEnvironment('COMPILE_TIME')) {
      compileTime = const int.fromEnvironment("COMPILE_TIME");
    } else {
      compileTime = DateTime.now().millisecondsSinceEpoch;
    }
    channel = const String.fromEnvironment("APP_CHANNEL", defaultValue: '');
  }

  // 测试使用
  late Map<String, dynamic> _envConfigs;

  List<MapEntry<String, dynamic>> get envConfigs => _envConfigs.entries.toList();

  /// --------------------------------- 固定配置 ---------------------------------------
  /// debug开关，上线需要关闭
  /// App运行在Release环境时，isDebug为false；当App运行在Debug和Profile环境时，isDebug为true
  static const bool is_debug = !const bool.fromEnvironment("dart.vm.product");

  static const int app_type_user = 1;

  /// TAG日志标签
  static const String log_tag = 'RIKI_TAG';

  static const int success_code = 1;

  static const String code = 'code';

  static const String message = 'message';

  static const String data = 'data';

  //IM和JPush发送的业务事件messageType 类型上限
  static const int messageTypeLimit = 17;

  static const String user_agent = 'dabanjia';

  /// 抖音渠道名称  !!!!! 此名称不要改
  static const String tiktokChannelName = 'tiktok';

  /// --------------------------------- 动态配置 ---------------------------------------
  late String _env; // 环境配置

  late int compileTime; // 编译时间
  late String appName; // app名称

  // 渠道名
  late String channel;

  //是否开启日志
  late bool pbLogOpen;

  // 获取环境配置文件
  String _getEnvFile() {
    if (_env == _dev) {
      return 'assets/config/.env.dev';
    } else if (_env == _stage) {
      return 'assets/config/.env.stage';
    } else if (_env == _test) {
      return 'assets/config/.env.test';
    } else if (_env == _release) {
      return 'assets/config/.env.release';
    }
    return 'assets/config/.env.dev';
  }

  // 初始化环境配置
  Future init() async {
    Map<String, dynamic> configs = {};
    String value = await rootBundle.loadString(_getEnvFile());
    value = value.replaceAll('\r', ''); //解决windows系统换行符问题
    List<String> list = value.split("\n");
    list.forEach((element) {
      if (element.contains("=")) {
        String key = element.substring(0, element.indexOf("="));
        String value = element.substring(element.indexOf("=") + 1);
        configs[key] = value;
      }
    });
    _log(configs);
    _parserConfig(configs);
    return Future.value();
  }

  void _log(Map msg) {
    if (_env != _release) {
      print('--------------------$_TAG--------------------');
      print('编译时间：${DateTime.fromMillisecondsSinceEpoch(compileTime).toString()}');
      print('-------------------环境配置内容--------------------');
      msg.forEach((key, value) {
        print('$key：$value');
      });
      print('--------------------$_TAG--------------------');
    }
  }

  void _parserConfig(Map<String, dynamic> configs) {
    configs['COMPILE_TIME'] = DateTime.fromMillisecondsSinceEpoch(compileTime).toString();
  }
}
